<?php namespace Phphub\Creators;

use Phphub\Forms\SectionCreationForm;
use Phphub\Core\CreatorListener;
use Phphub\Core\Robot;
use Lab;
use Section;
use Auth;
use Carbon;
use Markdown;

class SectionCreator
{
    protected $form;

    public function __construct(SectionCreationForm $form)
    {
        $this->form = $form;
    }

    public function create(CreatorListener $observer, $data)
    {
        $data['user_id'] = Auth::id();
        $data['created_at'] = Carbon::now()->toDateTimeString();
        $data['updated_at'] = Carbon::now()->toDateTimeString();

        $markdown = new Markdown;
        $data['body_original'] = $data['body'];
        $data['body'] = $markdown->convertMarkdownToHtml($data['body']);

        // Validation
        $this->form->validate($data);

        $section = Section::create($data);
        if (! $section) {
            return $observer->creatorFailed($section->getErrors());
        }

        return $observer->creatorSucceed($section);
    }
}
